package com.econ.powercloud.ems.service.biz.scene;

import com.alibaba.fastjson.JSONObject;
import com.econ.powercloud.console.facade.utils.CacheKeyUtils;
import com.econ.powercloud.datahandle.facade.domain.ProcessedCalData;
import com.econ.powercloud.datahandle.facade.domain.ProcessedRunData;
import com.econ.powercloud.ems.util.CalculationKeyUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author : zjf
 * @Description : 缓存业务处理类
 * @Date : 2021/7/5 15:32
 * @Modified by : zjf
 */
@Service
public class CacheBizService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取设备实时点号数据map
     * @param deviceCode
     * @param dits
     * @return
     */
    public Map<String, ProcessedRunData> getDeviceRunDataMap(String deviceCode, List<String> dits) {
        String cacheKey = CacheKeyUtils.getDeviceDataKey(deviceCode);
        return this.getDeviceDataMap(cacheKey, deviceCode, dits, ProcessedRunData.class);
    }

    /**
     * 获取虚拟设备点号数据map
     * @param deviceCode
     * @param dits
     * @return
     */
    public Map<String, ProcessedCalData> getDeviceCalDataMap(String deviceCode, List<String> dits){
        String cacheKey = CalculationKeyUtils.getDeviceDataKey(deviceCode);
        return this.getDeviceDataMap(cacheKey, deviceCode, dits, ProcessedCalData.class);
    }

    /**
     * 获取设备缓存数据
     * @param cacheKey
     * @param deviceCode
     * @param dits
     * @param clazz
     * @param <T>
     * @return
     */
    private <T> Map<String, T> getDeviceDataMap(String cacheKey, String deviceCode,
                                                                      List<String> dits, Class<T> clazz) {
        if (CollectionUtils.isEmpty(dits)) {
            return Collections.emptyMap();
        }
        List<String> pids = dits.stream().map(it -> deviceCode + "." + it).collect(Collectors.toList());
        HashOperations<String, String, String> hashOperations = stringRedisTemplate.opsForHash();
        List<String> results = hashOperations.multiGet(cacheKey, pids);
        Map<String, T> resultMap = new HashMap<>();
        for (int i = 0; i < pids.size(); i++) {
            String value = results.get(i);
            if (StringUtils.isBlank(value)) {
                continue;
            }
            resultMap.put(pids.get(i),JSONObject.toJavaObject(JSONObject.parseObject(value),clazz));
        }
        return resultMap;
    }

}
